package com.byzk.p2p.admin.fuiou.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.money.dto.RechargeRecord;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.util.RechargeStatus;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * 富友充值
 * @author suker
 *
 */

@Controller
@RequestMapping("/fuion/recharge")
@Scope("prototype")
public class FuionRechargeController extends BaseController{

	@Autowired
	private CallbackService callbackService;
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private UserService userService;
	
	@RequestMapping("/quick")
	public String quickPay(@RequestParam("userId")int userId,@RequestParam("amount") String amount) throws Exception{
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String mchnt_cd=Config.mchnt_cd;
		String mchnt_txn_ssn=DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000);
		User user=userService.getById(userId);
		String login_id=user.getPhone();
		String amt=Integer.parseInt(amount)*100+"";
		String page_notify_url=Config.server_url+"/account/recharge";
		String back_notify_url=Config.server_url+"/fuion/recharge/quick/callback";
		String signature=SecurityUtils.sign(amt + "|" + back_notify_url + "|" + login_id+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + page_notify_url);
	    response.setContentType("text/html;charset=UTF-8");
	    
	    String Url = Config.recharge_quick_url;
	    try {
	        out.println("<!DOCTYPE html>");
	        out.println("<html>");
	        out.println("<head>");
	        out.println("<title>Servlet RechargeServlet</title>");
	        out.println("</head>");
	        out.println("<body>");
	        out.println("<form action="+Url+" id=\"frm1\" method=\"post\">");
	        out.println("<input type=\"hidden\" name=\"mchnt_cd\" value='" + mchnt_cd + "'>");
	        out.println("<input type=\"hidden\" name=\"mchnt_txn_ssn\" value='" + mchnt_txn_ssn + "'>");
	        out.println("<input type=\"hidden\" name=\"login_id\" value='" + login_id + "'>");
	        out.println("<input type=\"hidden\" name=\"amt\" value='" + amt + "'>");
	        out.println("<input type=\"hidden\" name=\"page_notify_url\" value='" + page_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"back_notify_url\" value='" + back_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"signature\" value='" + signature + "'>");
	        out.println("</form>");
	        out.println("<script language=\"javascript\">");
	        out.println("document.getElementById(\"frm1\").submit();");
	        out.println("</script>");
	        out.println("</body>");
	        out.println("</html>");
	    } finally {
	        out.close();
	    }	
		return null;
	}
	
	@RequestMapping("/quick/callback")
	public String quickPayCallback(){
		String resp_code=request.getParameter("resp_code");
		String resp_desc=request.getParameter("resp_desc");
		String mchnt_cd=request.getParameter("mchnt_cd");
		String mchnt_txn_ssn=request.getParameter("mchnt_txn_ssn");
        String login_id=request.getParameter("login_id");
		String amt=request.getParameter("amt");
		String signature=request.getParameter("signature");
		 
		System.out.println("---------resp_code:"+resp_code);
		System.out.println("---------resp_desc:"+resp_desc);
		System.out.println("---------mchnt_cd:"+mchnt_cd);
		System.out.println("---------mchnt_txn_ssn:"+mchnt_txn_ssn);
		System.out.println("---------login_id:"+login_id);
		System.out.println("---------amt:"+amt);
		
		String str=resp_code + "|" + resp_desc+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + login_id+ "|" +amt + "|" +signature;
		
		Callback callback=new Callback("快捷充值",str,new Date());
		callbackService.saveOrUpdate(callback);
		
		if("0000".equals(resp_code)){
			List<RechargeRecord> recordList=rechargeService.getRecordByCode(mchnt_txn_ssn);
			if(recordList.size()==0){
				User user=userService.getUserByPhone(login_id);
				rechargeService.addRecharge(mchnt_txn_ssn,user.getId(), Double.parseDouble(amt)/100,"快捷充值","");
			}
		}else {
			addRechageFailure(mchnt_txn_ssn,login_id,Double.parseDouble(amt)/100,"快捷充值");
		}
		return null;
	}
	
	@RequestMapping("/web")
	public String webPay(@RequestParam("userId")int userId,@RequestParam("amount") String amount) throws Exception{
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String mchnt_cd=Config.mchnt_cd;
		String mchnt_txn_ssn=DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000);
		User user=userService.getById(userId);
		String login_id=user.getPhone();
		String amt=Integer.parseInt(amount)*100+"";
//		String page_notify_url=Config.server_url+"/account/recharge";
		String page_notify_url=Config.server_url+"/fuion/recharge/notifyR";
		String back_notify_url=Config.server_url+"/fuion/recharge/web/callback";
		String signature=SecurityUtils.sign(amt + "|" + back_notify_url + "|" + login_id+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + page_notify_url);
	    response.setContentType("text/html;charset=UTF-8");
	    System.out.println("充值操作，商户号码："+mchnt_cd+"流水号："+mchnt_txn_ssn+"充值金额："+amount); 
	    String Url = Config.recharge_pay_url;
	    try {
	        out.println("<!DOCTYPE html>");
	        out.println("<html>");
	        out.println("<head>");
	        out.println("<title>Servlet RechargeServlet</title>");
	        out.println("</head>");
	        out.println("<body>");
	        out.println("<form action="+Url+" id=\"frm1\" method=\"post\">");
	        out.println("<input type=\"hidden\" name=\"mchnt_cd\" value='" + mchnt_cd + "'>");
	        out.println("<input type=\"hidden\" name=\"mchnt_txn_ssn\" value='" + mchnt_txn_ssn + "'>");
	        out.println("<input type=\"hidden\" name=\"login_id\" value='" + login_id + "'>");
	        out.println("<input type=\"hidden\" name=\"amt\" value='" + amt + "'>");
	        out.println("<input type=\"hidden\" name=\"page_notify_url\" value='" + page_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"back_notify_url\" value='" + back_notify_url + "'>");
	        out.println("<input type=\"hidden\" name=\"signature\" value='" + signature + "'>");
	        out.println("</form>");
	        out.println("<script language=\"javascript\">");
	        out.println("document.getElementById(\"frm1\").submit();");
	        out.println("</script>");
	        out.println("</body>");
	        out.println("</html>");
	    } finally {
	        out.close();
	    }	
		return null;
	}
	
	
	@RequestMapping("/web/callback")
	public String webPayCallback() throws Exception{
		
		response.setContentType("text/xml"); 
		response.setCharacterEncoding("UTF-8"); 
        
		String resp_code=request.getParameter("resp_code");
		String resp_desc=request.getParameter("resp_desc");
		String mchnt_cd=request.getParameter("mchnt_cd");
		String mchnt_txn_ssn=request.getParameter("mchnt_txn_ssn");
        String login_id=request.getParameter("login_id");
		String amt=request.getParameter("amt");
		String rem=request.getParameter("rem");
		String signature=request.getParameter("signature");
		 
		System.out.println("---------resp_code:"+resp_code);
		System.out.println("---------resp_desc:"+resp_desc);
		System.out.println("---------mchnt_cd:"+mchnt_cd);
		System.out.println("---------mchnt_txn_ssn:"+mchnt_txn_ssn);
		System.out.println("---------login_id:"+login_id);
		System.out.println("---------amt:"+amt);
		System.out.println("---------rem:"+rem);
		
		String str=resp_code + "|" + resp_desc+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + login_id+ "|" +amt+ "|" + rem+ "|" +signature;
		Callback callback=new Callback("网银充值",str,new Date());
		callbackService.saveOrUpdate(callback);
		
		if("0000".equals(resp_code)){
			List<RechargeRecord> recordList=rechargeService.getRecordByCode(mchnt_txn_ssn);
			if(recordList.size()==0){
				User user=userService.getUserByPhone(login_id);
				rechargeService.addRecharge(mchnt_txn_ssn,user.getId(), Double.parseDouble(amt)/100,"网银充值","");
			}
		}else {
			addRechageFailure(mchnt_txn_ssn,login_id,Double.parseDouble(amt)/100,"网银充值");
		}
		return null;
	}
	
	/**
	 * 增加充值失败的记录
	 * @param mchnt_txn_ssn
	 * @param login_id
	 * @param amount
	 * @return
	 */
	public boolean addRechageFailure(String mchnt_txn_ssn,String login_id,Double amount,String method) {
		List<RechargeRecord> recordList=rechargeService.getRecordByCode(mchnt_txn_ssn);
		if(recordList.size()==0){
			User user=userService.getUserByPhone(login_id);
			RechargeRecord record=new RechargeRecord();
			record.setBalance(amount);
			record.setCreateTime(new Date());
			record.setFee(0.0);
			record.setMoney(amount);
			record.setPayMethod(method);
			record.setUserId(user.getId());
			record.setTerminal("PC");
			record.setCode(mchnt_txn_ssn);
			record.setStatus(RechargeStatus.FAILURE);
			record.setPayTime(new Date());
			rechargeService.saveOrUpdate(record);
			return true;
		}
		return false;
	}
	
	/**
	 * 
	* <p>Description:充值接口调用通知信息 </p>
	* <p>Company:xbd </p>
	* @author:lilei
	 * @throws IOException 
	* @date:2016年12月9日上午9:57:59
	 */
	@RequestMapping("/notifyR")
	public void  notifyR() throws IOException{
		String resp_code=request.getParameter("resp_code");
		String resp_desc=request.getParameter("resp_desc");
		String mchnt_cd=request.getParameter("mchnt_cd");
		String mchnt_txn_ssn=request.getParameter("mchnt_txn_ssn");
        String login_id=request.getParameter("login_id");
		String amt=request.getParameter("amt");
		String rem=request.getParameter("rem");
		String signature=request.getParameter("signature");
		
		System.out.println("resp_code:"+resp_code+"resp_desc:"+resp_desc+"mchnt_cd:"+mchnt_cd+
				          "mchnt_txn_ssn:"+mchnt_txn_ssn+"login_id:"+login_id+"amt:"+amt+"rem:"+rem+"signature:"+signature);
		response.sendRedirect(Config.server_url+"/account/recharge");
	}
	
	
	/**
	 * app 快速充值回调
	 * @return
	 */
	@RequestMapping("/speedy/callback")
	public String speedyPayCallback(){
		String resp_code=request.getParameter("resp_code");
		String resp_desc=request.getParameter("resp_desc");
		String mchnt_cd=request.getParameter("mchnt_cd");
		String mchnt_txn_ssn=request.getParameter("mchnt_txn_ssn");
        String login_id=request.getParameter("login_id");
		String amt=request.getParameter("amt");
		String signature=request.getParameter("signature");
		 
		System.out.println("---------快速充值回调resp_code:"+resp_code);
		System.out.println("---------快速充值回调resp_desc:"+resp_desc);
		System.out.println("---------快速充值回调mchnt_cd:"+mchnt_cd);
		System.out.println("---------快速充值回调mchnt_txn_ssn:"+mchnt_txn_ssn);
		System.out.println("---------快速充值回调login_id:"+login_id);
		System.out.println("---------快速充值回调amt:"+amt);
		
		String str=resp_code + "|" + resp_desc+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + login_id+ "|" +amt + "|" +signature;
		
		Callback callback=new Callback("快速充值",str,new Date());
		callbackService.saveOrUpdate(callback);
		
		if("0000".equals(resp_code)){
			List<RechargeRecord> recordList=rechargeService.getRecordByCode(mchnt_txn_ssn);
			if(recordList.size()==0){
				User user=userService.getUserByPhone(login_id);
				rechargeService.addRecharge(mchnt_txn_ssn,user.getId(), Double.parseDouble(amt)/100,"快速充值","");
			}
		}else {
			addRechageFailure(mchnt_txn_ssn,login_id,Double.parseDouble(amt)/100,"快速充值");
		}
		return null;
	}
}
